package xyz.syyrjx.blog.service.tools.impl;

import org.springframework.stereotype.Service;
import xyz.syyrjx.blog._enum.State;
import xyz.syyrjx.blog.dao.tool.shakeRice.FoodDao;
import xyz.syyrjx.blog.entity.Food;
import xyz.syyrjx.blog.service.tools.FoodService;
import xyz.syyrjx.blog.util.CachePool;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

@Service
public class FoodServiceImpl implements FoodService {
    @Resource
    private FoodDao dao;

    @Override
    public List<Food> getFoods(Food template) {
        template.setState(State.NORMAL_STATE.getCode());
        return dao.selectFoods(template);
    }

    @Override
    public Food getFoodByName(Food template) {
        Food temp = template.copy();
        temp.setId(null);
        temp.setState(State.NORMAL_STATE.getCode());
        List<Food> foods = dao.selectFoods(temp);
        return foods.stream().findFirst().orElse(null);
    }

    @Override
    public void addFood(Food foodIn) {
        foodIn.setState(State.NORMAL_STATE.getCode());
        dao.insertFood(foodIn);
        CachePool.setAllFood(null);
    }

    @Override
    public List<String> getAllName() {
        if (CachePool.getAllFood() == null) {
            Food template = new Food();
            template.setState(State.NORMAL_STATE.getCode());
            CachePool.setAllFood(dao.selectFoods(template)
                    .stream()
                    .map(Food::getFood)
                    .collect(Collectors.toList()));
        }
        return CachePool.getAllFood();
    }
}
